#!/usr/bin/env python3
"""
Intelligent Rules V2.0 统一演示工具
基于简洁优先原则，合并所有demo功能到一个精简文件

核心功能：
1. 智能演进引擎演示
2. 智能监控系统演示  
3. 自我验证演示

遵循5个核心规则：
- simplicity_first_principle.yaml: 简洁优先，避免重复
- enterprise_security_framework.yaml: 安全验证
- enterprise_testing_quality_assurance.yaml: 质量保证
- unified_configuration_management.yaml: 配置管理
- practice_driven_evolution_rules.yaml: 实践驱动
"""

import sys
import os
from pathlib import Path

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

# 安全导入 - 符合enterprise_security_framework.yaml
try:
    from foundation.core.security_validator import security_validator
    from foundation.core.intelligent_evolution_engine import IntelligentEvolutionEngine
    from foundation.core.intelligent_monitoring_system import IntelligentMonitoringSystem
    from foundation.core.rule_engine import RuleEngine
except ImportError as e:
    print(f"❌ 导入错误: {e}")
    print("请确保在项目根目录运行此脚本")
    sys.exit(1)

class IntelligentRulesDemo:
    """Intelligent Rules V2.0 统一演示器"""
    
    def __init__(self):
        self.project_root = project_root
        print("🚀 Intelligent Rules V2.0 统一演示")
        print("=" * 60)
        
    def demo_evolution_engine(self):
        """演示智能演进引擎"""
        print("\n1️⃣ 智能演进引擎演示")
        print("-" * 30)
        
        try:
            engine = IntelligentEvolutionEngine()
            print("✅ 智能演进引擎初始化成功")
            
            # 运行智能闭环演进周期
            result = engine.start_intelligent_evolution_cycle()
            
            # 获取验证阶段的评分
            validation_phase = next((p for p in result.get('phases', []) if p['phase'] == 'self_validation'), None)
            score = validation_phase['result']['overall_score'] if validation_phase else 'N/A'
            
            print(f"📊 演进评分: {score}/100")
            print(f"✅ 状态: {result.get('status', 'unknown')}")
            
        except Exception as e:
            print(f"❌ 演进引擎演示失败: {e}")
    
    def demo_monitoring_system(self):
        """演示智能监控系统"""
        print("\n2️⃣ 智能监控系统演示")
        print("-" * 30)
        
        try:
            monitor = IntelligentMonitoringSystem()
            print("✅ 智能监控系统初始化成功")
            
            # 启动监控并收集指标
            monitor.start_monitoring()
            status = monitor.get_monitoring_status()
            
            print(f"📊 监控状态: {status.get('status', 'unknown')}")
            print(f"📊 监控指标: {len(status.get('metrics', {}))}个")
            print("✅ 智能监控系统运行正常")
            
        except Exception as e:
            print(f"❌ 监控系统演示失败: {e}")
    
    def demo_security_validation(self):
        """演示安全验证系统"""
        print("\n3️⃣ 安全验证系统演示")
        print("-" * 30)
        
        try:
            # 测试输入验证
            test_inputs = [
                "rules/core/test.yaml",  # 安全输入
                "../../../etc/passwd",   # 路径遍历攻击
                "<script>alert('xss')</script>",  # XSS攻击
                "exec('rm -rf /')",     # 代码执行攻击
            ]
            
            safe_count = 0
            for test_input in test_inputs:
                is_safe = security_validator.validate_input(test_input)
                status = "✅ 安全" if is_safe else "❌ 危险(已阻止)"
                print(f"  {status}: {test_input[:30]}...")
                if is_safe:
                    safe_count += 1
            
            print(f"📊 安全验证成功率: {safe_count}/{len(test_inputs)}")
            
        except Exception as e:
            print(f"❌ 安全验证演示失败: {e}")
    
    def demo_rules_engine(self):
        """演示规则引擎"""
        print("\n4️⃣ 规则引擎演示")
        print("-" * 30)
        
        try:
            engine = RuleEngine()
            print("✅ 规则引擎初始化成功")
            
            # 显示规则统计
            all_rules = engine.get_all_rules()
            print(f"📊 已加载规则数量: {len(all_rules)}")
            
            # 按类别显示规则
            categories = ["core", "system", "evolution", "validation"]
            for category in categories:
                rules = engine.get_rules_by_category(category)
                print(f"  {category}: {len(rules)}个规则")
                
        except Exception as e:
            print(f"❌ 规则引擎演示失败: {e}")
    
    def demo_quality_metrics(self):
        """演示质量指标"""
        print("\n5️⃣ 质量保证演示")
        print("-" * 30)
        
        try:
            # 代码文件统计
            py_files = list(self.project_root.rglob("*.py"))
            yaml_files = list(self.project_root.rglob("*.yaml"))
            
            print(f"📊 Python文件: {len(py_files)}个")
            print(f"📊 YAML规则文件: {len(yaml_files)}个")
            
            # 计算总代码行数
            total_lines = 0
            for py_file in py_files:
                try:
                    with open(py_file, 'r', encoding='utf-8') as f:
                        total_lines += len(f.readlines())
                except:
                    continue
            
            print(f"📊 总代码行数: {total_lines}")
            print(f"📊 平均文件大小: {total_lines // len(py_files) if py_files else 0}行")
            
            # 简洁性评估
            if total_lines <= 4000:
                print("✅ 符合简洁优先原则 (≤4000行)")
            else:
                print("⚠️ 需要进一步简化")
                
        except Exception as e:
            print(f"❌ 质量指标演示失败: {e}")
    
    def run_all_demos(self):
        """运行所有演示"""
        demos = [
            self.demo_evolution_engine,
            self.demo_monitoring_system,
            self.demo_security_validation,
            self.demo_rules_engine,
            self.demo_quality_metrics,
        ]
        
        for demo in demos:
            try:
                demo()
            except Exception as e:
                print(f"❌ 演示失败: {e}")
                continue
        
        print("\n🎉 所有演示完成！")
        print("=" * 60)
        print("📝 总结:")
        print("  - Intelligent Rules V2.0 作为通用底座运行正常")
        print("  - 5个核心规则得到有效实施")  
        print("  - 安全、质量、简洁性得到保障")
        print("  - 准备好指导新项目开发！")


def main():
    """主函数"""
    if len(sys.argv) > 1 and sys.argv[1] in ['--help', '-h']:
        print("Intelligent Rules V2.0 统一演示工具")
        print("\n用法:")
        print("  python tools/intelligent_rules_demo.py")
        print("\n功能:")
        print("  - 演示智能演进引擎")
        print("  - 演示智能监控系统") 
        print("  - 演示安全验证系统")
        print("  - 演示规则引擎")
        print("  - 演示质量保证")
        return
    
    demo = IntelligentRulesDemo()
    demo.run_all_demos()


if __name__ == "__main__":
    main() 